/*
 * MySqlManager.cpp
 *
 *  Created on: Feb 24, 2014
 *      Author: root
 */

#include "MySqlManager.h"
#include <iostream>
#include <cstring>
using namespace std;

namespace miniGameServer {

MySqlManager::MySqlManager() {
	init();
}

MySqlManager::MySqlManager(const MySqlManager& msm)
{

}
MySqlManager& MySqlManager::operator=(const MySqlManager& msm)
{
	if(this != &msm)
	{

	}
	return *this;
}

MySqlManager::~MySqlManager() {
	destory();
}

MySqlManager& MySqlManager::instance()
{
	static MySqlManager _instance;
	return _instance;
}

void MySqlManager::init()
{
	mysql_init(&mysql);
	cout<<"sql init finish"<<endl;
}

void MySqlManager::destory()
{
	mysql_close(&mysql);
	cout<<"mysql closed "<<endl;
}

int MySqlManager::connect(const char *user,const char *psw,const char *dbname,const char *host,const int port)
{

	if(mysql_real_connect(&mysql,host,user,psw,dbname,port,NULL,0) == NULL)
	{
		cout<<"sql connect error"<<mysql_error(&mysql)<<endl;
		return 1;
	}
	cout<<"sql connect success"<<endl;
	return 0;
}

int MySqlManager::selectQuery(const char *sqlStatement)
{
	if(mysql_real_query(&mysql,sqlStatement,strlen(sqlStatement)) != 0)
	{
		cout<<"query error"<<endl;
		return -1;
	}
	if(m_result != NULL)
	{
		mysql_free_result(m_result);
		m_result = NULL;
	}
	m_result = mysql_store_result(&mysql);
	return 0;
}

int MySqlManager::modifyQuery(const char *sqlStatement)
{
	if(mysql_real_query(&mysql,sqlStatement,strlen(sqlStatement)) != 0)
	{
		cout<<"query error"<<endl;
		return -1;
	}
	return 0;
}

char ** MySqlManager::fetchRow()
{
	if(m_result == NULL)
	{
		return NULL;
	}
	row = mysql_fetch_row(m_result);
	return row;
}

}
